package com.mycompony.shopping.shangguan.sys.context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.mycompony.shopping.shangguan.sys.model.Auth;
import com.mycompony.shopping.shangguan.sys.model.Role;
import com.mycompony.shopping.shangguan.sys.model.User;
import com.mycompony.shopping.shangguan.sys.service.AuthRoleService;
import com.mycompony.shopping.shangguan.sys.service.UserAuthService;
import com.mycompony.shopping.shangguan.sys.service.UserRoleService;

public class UserAuthContext {

	protected static UserRoleService userRoleService = (UserRoleService) ApplicationContextUtil
			.getBean("userRoleService");

	protected static UserAuthService userAuthService = (UserAuthService) ApplicationContextUtil
			.getBean("userAuthService");

	protected static AuthRoleService authRoleService = (AuthRoleService) ApplicationContextUtil
			.getBean("authRoleService");

	public static synchronized Map<String, Auth> getAuthMap(User user) {

		Map<String, Auth> authResultMap = new HashMap<String, Auth>();

		Map<String, Role> roleMap = userRoleService.getUserAllRole(user);

		Map<String, Auth> authMap = userAuthService.getUserAllAuth(user);

		authResultMap.putAll(authMap);

		List<Auth> authlist = new ArrayList<Auth>();

		if (roleMap != null && !roleMap.isEmpty()) {

			Iterator<String> keys = roleMap.keySet().iterator();

			while (keys.hasNext()) {
				String key = keys.next();
				Role role = roleMap.get(key);
				List<Auth> tempAuthList = authRoleService
						.getAuthListByRole(role);
				if (tempAuthList != null && !tempAuthList.isEmpty()) {
					authlist.addAll(tempAuthList);
				}
			}

		}

		if (authlist != null && !authlist.isEmpty()) {
			for (Auth auth : authlist) {

				if (auth == null || StringUtils.isEmpty(auth.getAuthid())) {
					break;
				}

				authResultMap.put(auth.getAuthid(), auth);
			}
		}

		return authResultMap;

	}

	public static synchronized List<Auth> getAuthList(User user) {

		List<Auth> authlist = new ArrayList<Auth>();

		Map<String, Auth> authResultMap = getAuthMap(user);

		if (authResultMap == null || authResultMap.isEmpty()) {
			return null;
		}

		Iterator<String> keys = authResultMap.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			Auth auth = authResultMap.get(key);
			if (auth == null || StringUtils.isEmpty(auth.getAuthid())) {
				break;
			}
			authlist.add(auth);
		}
		return authlist;
	}

}
